<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<script type="text/javascript">
	var attachId = "${param.attachId}";
	var isNeedUpdate = false;
	var simUploadLimit = 1;
	if(attachId) {
		simUploadLimit = 5;
	} else {
		isNeedUpdate = true;
	}

	function getOptionAttach() {
		return {
			width : 'auto',
			height : '325',
			fitColumns : true,
			nowrap : false,
			striped : true,
			url : '${ctx}/sys/attach/attach!queryList.action',
			queryParams:{"attachId":attachId},
			sortName : 'id',
			sortOrder : 'desc',
			remoteSort: true,
			idField : 'id',
			pageSize: 5,
			pageList: [5, 10, 20],
			frozenColumns : [ [ {
				field : 'ck',
				checkbox : true
			}  ] ],
			columns : [ [ {
				field : 'fileName',
				title : '<s:text name="system.attach.attachName.title"/>',
				width : 180,
				sortable : true
			}, {
				field : 'fileSize',
				title : '<s:text name="system.attach.attachSize.title"/>(B)',
				width : 100,
				sortable : true
			}, {
				field : 'createUser',
				title : '<s:text name="system.sysmng.user.createuser.title"/>',
				width : 120,
				sortable : true,
				formatter : function(value, rowData, rowIndex){	
                    /*var uObj=_userList[value];
                    if(uObj){
                    	var nickName = (uObj.nickName)?("-" + uObj.nickName):"";
						return uObj.realName + "[" + uObj.loginName + "]" + nickName;
                    }else{
                        return value;
                    }*/
                    return rowData["createUserCaption"];
				}
			}, {
				field : 'createTime',
				title :  '<s:text name="system.sysmng.user.createtime.title"/>',
				width : 120,
				sortable : true
			},{
				field : 'oper',
				title : '<s:text name="system.button.oper.title"/>',
				width : 80,
				align : 'left',
				formatter : operFormatterAttach
			} ] ],
			pagination : true,
			rownumbers : true,
			//if("${param.readOnly}" == true){
			toolbar : [ 
			{
				id : 'bt_batch_download',
				text : '<s:text name="批量下载"/>',
				iconCls : 'icon-download-ico',
				handler : function() {
					doDownloadAttach();
				}
			},'-'
			<c:if test="${param.readOnly=='false'}">
			,{
				id : 'bt_del',
				text : '<s:text name="system.button.batchDelete.title"/>',
				iconCls : 'icon-remove',
				handler : function() {
					doDeleteIdsAttach();
				}
			}
			</c:if>
			],
			onDblClickRow :function(rowIndex, rowData){
				var url = "${systemParam.virtualPicPath}"+ rowData.filePath;
				window.open(url);
			}
		};
	}
	function doDeleteIdsAttach() {
		var ids = [];
		var rows = $("#attachList").datagrid('getSelections');
		for ( var i = 0; i < rows.length; i++) {
			ids.push(rows[i].id);
		}
		if (ids != null && ids.length > 0) {
			doDeleteAttach(ids);
		} else {
			$.messager.alert(
					'<s:text name="system.javascript.alertinfo.title"/>',
					'<s:text name="system.javascript.alertinfo.question"/>',
					'info');
		}
	}
	function operFormatterAttach(value, rowData, rowIndex) {
		return '<a href="'
		+ "${systemParam.virtualPicPath}"
		+ rowData.filePath
		+ '" target= "_blank") ><s:text name="system.button.view.title"/></a>&nbsp;'
		<c:if test="${param.readOnly=='false'}">
		+'<a href="javascript:void(0);" onclick="doDeleteAttach('
				+ rowData.id
				+ ')"><s:text name="system.button.delete.title"/></a>'
		</c:if>;
	}
	//删除附件文件
	function doDeleteAttach(ids) {
		$.messager
				.confirm(
						'<s:text name="system.javascript.alertinfo.title"/>',
						'<s:text name="system.javascript.alertinfo.info"/>',
						function(r) {
							if (r) {
								var options = {
									url : '${ctx}/sys/attach/attach!delete.action',
									data : {
										"ids" : ids
									},
									traditional : true ,									
									success : function(data) {
										
									if (!data.msg) {	
										if (window.doUpdateAttach) {
											$("#attachId").val("");
											var opts ={"attachId":"",
							           				 "id":"${param.bid}",
							           				 "key":"${param.key}",
							           				 "entityName":"${param.entityName}",
							           				 "dgId":"${param.dgId}",
							           				 "flag":"${param.flag}",
							           				 "readOnly" :"${param.readOnly}"
							           					};
							window.doUpdateAttach(opts);
													} 
										isNeedUpdate = true;
										}
									$("#attachList").datagrid('clearSelections');
									$("#attachList").datagrid("load");	
									}
								};
								fnFormAjaxWithJson(options);
							}
						});
	}
	function downloadFile(url) {   
		try{ 
			var elemIF = document.createElement("iframe");   
			elemIF.src = url;   
			elemIF.style.display = "none";   
			document.body.appendChild(elemIF);   
		} catch(e){ 
	
		} 
	}  
	
	function getDownloadFileUrl(fileName, filePath) {
		var downUrl = ["${ctx}/sys/attach/upload-file!downloadFile.action?filedataFileName="];
		downUrl.push(encodeURIComponent(fileName));
		downUrl.push("&filePath=");
		downUrl.push(encodeURIComponent(filePath));
		return downUrl.join("");
	}
	
	//批量下载文件
	function doDownloadAttach() {
		var rows = $("#attachList").datagrid('getSelections');
		if (rows && rows.length) {
			for(var i=0,len=rows.length;i<len;i++) {
				var rowData = rows[i];
				//var url = "/jwpf/upload/gs-attach/"+ rowData.filePath;
				//var url = "${systemParam.virtualPicPath}"+ rowData.filePath;
				var url = getDownloadFileUrl(rowData.fileName, rowData.filePath);
				downloadFile(url);
				//console.log(rowData.id);
				//window.open(url, "附件" + rowData.id);
			}
		} else {
			$.messager.alert(
					'<s:text name="system.javascript.alertinfo.title"/>',
					'<s:text name="system.javascript.alertinfo.operRecord"/>',
					'info');
		}
	}
	//添加上传附件文件
	function doAddAttach() {
		var attId = $("#attachId").val();
		if(!attId) {
			var options = {
					url : '${ctx}/sys/attach/attach!save.action',
					async: false,
					success : function(data) {
						if(data.msg) {
							$("#attachId").val(data.msg);
							$("#file_upload").uploadify("settings", "formData", {"attachId":data.msg});
							$('#file_upload').uploadify('upload','*');
						}
					}
			};
			fnFormAjaxWithJson(options);
		} else {
			$("#file_upload").uploadify("settings", "formData", {"attachId":attId});
			$('#file_upload').uploadify('upload','*');
		}
	}
	var _userList={}; 
	$(document)
			.ready(
					function() {
				  //_userList=findAllUser();  
				  //uploadify插件初始化设置
						$("#file_upload")
								.uploadify(
										{
											'uploader' : '${ctx}/sys/attach/upload-file!save.action;jsessionid=<%=session.getId()%>',
											'swf' : '${ctx}/js/uploadify/uploadify-3.1.swf',
											'cancelImg' : '${ctx}/js/uploadify/uploadify-cancel-3.1.png',
											'queueID' : 'uploadGsQueue',
											'auto' : false,
											'multi' : true,
											'width' : 95,
											'height' : 20,
											'buttonClass' : 'uploadify-button-small',
											'fileSizeLimit' : '50MB', //限制上传的文件大小
											'fileTypeExts' : '*.*;', //允许的格式 
											/**	'onCancel' : function(event,
														queueId, fileObj, data) {
													$.messager.alert("取消 " + "[" + file.name
															+ "]" + "文件上传");
												},
											 */
											'onUploadSuccess' : function(file,
													data, response) {
												// 	alert("文件:" + "["+file.name +"]"+ "上传成功");
												if(data) {
													var msg = $.parseJSON(data);
													if(msg && msg.flag == "1") {
														if(msg.msg != $("#attachId").val()) {
															$("#attachId").val(msg.msg);
															isNeedUpdate = true;
														}
													} else if(msg && msg.msg) {
														$.messager.alert("<s:text name="system.javascript.alertinfo.titleInfo"/>", '文件'
																+ file.name
																+ '上传失败，错误信息如下：'
																+ msg.msg,
																"warning");
													}
												}
											},
											'onUploadError' : function(file,
													errorCode, errorMsg,
													errorString) {
												$.messager.alert("<s:text name="system.javascript.alertinfo.titleInfo"/>", '文件'
														+ file.name
														+ '上传失败，错误信息如下：'
														+ errorString,
														"warning");
											},
											'onQueueComplete' : function(
													queueData) {				
												//alert(queueData.uploadsSuccessful + ' files were successfully uploaded.');
												var aId = $("#attachId").val();
												if (isNeedUpdate) {//更新业务表附件字段
													if (window.doUpdateAttach) {
														var opts ={"attachId":aId,
										           				 "id":"${param.bid}",
										           				 "key":"${param.key}",
										           				 "entityName":"${param.entityName}",
										           				 "dgId":"${param.dgId}",
										           				 "flag":"${param.flag}",
										           				 "readOnly" :"${param.readOnly}"
										           					};
										window.doUpdateAttach(opts);
													}
													isNeedUpdate = false;
												}
												$("#attachList")
														.datagrid(
																"reload",
																{
																	"attachId" : aId
																});
											}/*,
																				        'onUploadStart' : function(file) {
																					        alert(file.name + $("#attachId").val());
																				            
																				        }*/
										});

						$("#attachList").datagrid(getOptionAttach());	
						$("#bt_upload_gs").click(function() {
							doAddAttach();
						});
					});
</script>
<div class="easyui-layout" fit="true">
	<div region="center" style="padding: 3px 2px" border="false">
		<c:if test="${param.readOnly=='false' || param.readOnly=='onlyUpload'}">
		<div class="file_upload_button">
			<input type="file" name="uploadify_gs" id="file_upload" />
			<button class="upload-button-1 button_big" id="bt_upload_gs"
				type="button"><s:text name="system.button.startUpload.title"/></button>
			<span class="upload-button-3">[注：添加附件时，可用Ctrl或Shift+鼠标左键来选择多个文件]</span>
		</div>
		</c:if>
		<div id="uploadGsQueue" class="file_upload_queue"></div>
		<table id="attachList">
		</table>
		<div style="display: none;">
			<input type="hidden" name="attachId" id="attachId"
				value="${param.attachId}" />
		</div>
	</div>
</div>




